package com.stuffthathappens.concurrency;

import java.util.concurrent.*;

/**
 * @author Eric Burke
 */
public class DonutDemo {

    public static void main(String[] args) throws InterruptedException {
        final ExecutorService executorService =
                Executors.newCachedThreadPool(new SampleThreadFactory("donuts"));

        BlockingQueue<Donut> donutQueue = new LinkedBlockingQueue<Donut>(10);

        // NOTE: Even if you make the producers a LOT faster, the queue prevents
        // them from flooding the market with stale donuts

        executorService.execute(new DonutProducer("Krispy Kreme", donutQueue,
                TimeUnit.MILLISECONDS, 500));

        executorService.execute(new DonutProducer("Heaven Scent", donutQueue,
                TimeUnit.MILLISECONDS, 2000));


        final DonutConsumer homer = new DonutConsumer("Homer", donutQueue,
                TimeUnit.SECONDS, 1);
        final DonutConsumer barney = new DonutConsumer("Barney", donutQueue,
                TimeUnit.SECONDS, 4);

        executorService.execute(homer);
        executorService.execute(barney);

        // minutes (and hours, days) added in Java 6
        TimeUnit.SECONDS.sleep(30);

        System.out.println("----------------------------------------");
        Thread[] arr = new Thread[Thread.activeCount()];
        Thread.enumerate(arr);
        for (Thread t : arr) {
            if (t != null) {
                System.out.println(t.getName());
            }
        }
        System.out.println("----------------------------------------");

        executorService.shutdownNow();

        System.out.println("Done!");
        System.out.format("%s ate %d donuts.%n", homer.getName(), homer.getNumAte());
        System.out.format("%s ate %d donuts.%n", barney.getName(), barney.getNumAte());
    }
}
